package nckd.wnqjt.tmc.tda.plugin.form;

import kd.bos.algo.DataSet;
import kd.bos.algo.Row;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.report.AbstractReportListDataPlugin;
import kd.bos.entity.report.FilterInfo;
import kd.bos.entity.report.FilterItemInfo;
import kd.bos.entity.report.ReportQueryParam;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.QueryServiceHelper;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhujintao
 * @date 2024/11/05
 * @desc 银行借款增减变动
 */
public class ChangesBankLoanListDataPlugin extends AbstractReportListDataPlugin {

    @Override
    public DataSet query(ReportQueryParam reportQueryParam, Object o) throws Throwable {
        FilterInfo filterInfo = reportQueryParam.getFilter();
        FilterItemInfo org = filterInfo.getFilterItem("nckd_org");
        Object value = org.getValue();
        DynamicObjectCollection nckdOrg = null;
        if (value != null) {
            nckdOrg = (DynamicObjectCollection) value;
        }
        String selectField = "billno,org,textcreditor,bizdate,drawamount";
        //获取当前日期，用于计算3个月的日期
        LocalDate currentDate = LocalDate.now();
        //int currentMonth = currentDate.getMonthValue();
        //获取当前年份的第一天
        LocalDate firstDayOfYear = currentDate.withDayOfYear(1); // 获取当前年份的第一天
        //格式化日期为所需的格式
        Date startdate = Date.from(firstDayOfYear.atTime(0, 0, 0).atZone(ZoneId.systemDefault()).toInstant());
        Date enddate = Date.from(currentDate.atTime(23, 59, 59).atZone(ZoneId.systemDefault()).toInstant());
        QFilter filter = new QFilter("loantype", QCP.in, Arrays.asList("loan", "sl"))
                .and("billstatus", QCP.equals, "C")
                //.and("drawtype", QCP.not_equals, "closeout")
                .and("repayplan_entry.enotrepayamount", QCP.large_than, 0)
                .and("bizdate", QCP.large_than, startdate)
                .and("bizdate", QCP.less_equals, enddate);
        if (nckdOrg != null) {
            List<Long> longList = nckdOrg.stream().map(e -> e.getLong("id")).collect(Collectors.toList());
            filter.and("org", QCP.in, longList);
        }
        DataSet dataSet = QueryServiceHelper.queryDataSet(this.getClass().getName(), "cfm_loanbill", selectField, filter.toArray(), null);
        dataSet = dataSet.addBalanceField("0", "amount");
        DataSet copy = dataSet.copy();
        List<String> listBillno = new ArrayList<>();
        while (copy.hasNext()) {
            Row next = copy.next();
            listBillno.add(next.getString("billno"));
        }

        String selectField1 = "org,textcreditor,bizdate,amount";
        QFilter filter1 = new QFilter("loantype", QCP.in, Arrays.asList("loan", "sl"))
                .and("billstatus", QCP.equals, "C")
                .and("bizdate", QCP.large_than, startdate)
                .and("bizdate", QCP.less_equals, enddate);
                //.and("loans.e_loanbill.number", QCP.in, listBillno);
        if (nckdOrg != null) {
            List<Long> longList = nckdOrg.stream().map(e -> e.getLong("id")).collect(Collectors.toList());
            filter1.and("org", QCP.in, longList);
        }
        DataSet dataSet1 = QueryServiceHelper.queryDataSet(this.getClass().getName(), "cfm_repaymentbill", selectField1, filter1.toArray(), null);
        dataSet1 = dataSet1.addBalanceField("0", "drawamount");

        DataSet unionDataSet = dataSet.select("org", "textcreditor", "bizdate", "drawamount", "amount").union(dataSet1.select("org", "textcreditor", "bizdate", "drawamount", "amount"));
        unionDataSet = unionDataSet.addField("TO_CHAR(bizdate,'yyyy-MM')", "yearmonth");
        unionDataSet = unionDataSet.addField("0", "sort");
        //月合计
        DataSet monthgroupDataSet = unionDataSet.copy().groupBy(new String[]{"yearmonth"}).sum("drawamount").sum("amount").finish();
        monthgroupDataSet = monthgroupDataSet.addNullField("org");
        monthgroupDataSet = monthgroupDataSet.addField("'本月合计'", "textcreditor");
        monthgroupDataSet = monthgroupDataSet.addField("1", "sort");
        //年合计
        DataSet yeargroupDataSet = unionDataSet.copy().groupBy().sum("drawamount").sum("amount").finish();
        yeargroupDataSet = yeargroupDataSet.addNullField("org", "yearmonth");
        yeargroupDataSet = yeargroupDataSet.addField("'本年合计'", "textcreditor");
        yeargroupDataSet = yeargroupDataSet.addField("2", "sort");

        DataSet union = unionDataSet.select("org", "textcreditor", "drawamount", "amount", "yearmonth", "sort")
                .union(monthgroupDataSet.select("org", "textcreditor", "drawamount", "amount", "yearmonth", "sort"));
        DataSet result = union.orderBy(new String[]{"yearmonth", "sort"}).select("org", "textcreditor", "drawamount", "amount", "yearmonth", "sort")
                .union(yeargroupDataSet.select("org", "textcreditor", "drawamount", "amount", "yearmonth", "sort"));
        result = result.updateField("drawamount", "drawamount / 10000");
        result = result.updateField("amount", "amount / 10000");
        return result;
    }
}